package zl_service

import (
	"bytes"
	"encoding/json"
	"fmt"
	"github.com/goravel/framework/facades"
	"github.com/goravel/framework/support/carbon"
	"goravel/app/models"
	"io/ioutil"
	"net/http"
)

const (
	REFUND_URL = "/zl.open.api.oms.pos.order.refund.v5/1.0.0/action"
)

type RefundOrderService struct {
}

type RefundParams struct {
	AppKey     string                  `json:"appkey"`
	Signtime   string                  `json:"signtime"`
	Returncode string                  `json:"returncode" comment:"原销售单的请求流水号"`
	Paytotal   string                  `json:"paytotal" comment:"退款总金额"`
	Remark     string                  `json:"remark" comment:"退款备注"`
	Reason     string                  `json:"reason" comment:"退款理由"`
	Commoditys []models.OrderCommodity `json:"commoditys" comment:"商品行"`
}

// 开退货单
func (b *RefundOrderService) CreateRefundOrder(order models.Order) error {
	url := BASE_URL + REFUND_URL
	client := &http.Client{}
	// 请求参数结构体，对应要发送的JSON数据格式
	orderParams := RefundParams{
		AppKey:     APP_KEY,
		Signtime:   carbon.NewDateTime(carbon.Now()).Format("Y-m-d H:i:s"),
		Returncode: order.Ticketcode,
		Paytotal:   order.Paytotal,
		Remark:     "小程序退款",
		Reason:     "客户退款",
		Commoditys: order.Commoditys,
	}

	bodyBytes, _ := json.Marshal(orderParams)
	stringToSign := fmt.Sprintf("%s&appsecret=%s", string(bodyBytes), APP_SECRET)
	facades.Log().Info("向进销存发送退库信号", order)
	upperSign := ComputeMD5AndToUpper(stringToSign)
	req, err := http.NewRequest("POST", url, bytes.NewBuffer(bodyBytes))
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("Request-Sign", upperSign)
	body, err := client.Do(req)
	if err != nil {
		return err
	}
	defer body.Body.Close()
	//将body
	res, err := ioutil.ReadAll(body.Body)
	facades.Log().Info("向进销存发送退库信号==OK回执", string(res))
	return nil
}
